package com.ruoyi.file.service;

import java.io.InputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.ruoyi.file.config.OssConfig;
import com.ruoyi.file.utils.FileUploadUtils;

/**
 * OSS文件存储服务
 *
 * @author ruoyi
 */
@Service("ossSysFileServiceImpl")
public class OssSysFileServiceImpl implements ISysFileService
{
    @Autowired
    private OSS ossClient;

    @Autowired
    private OssConfig ossConfig;

    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 生成文件名
            String fileName = FileUploadUtils.extractFilename(file);
            String objectName = "ruoyi/" + fileName;

            // 设置对象元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());

            // 上传文件
            try (InputStream inputStream = file.getInputStream())
            {
                ossClient.putObject(ossConfig.getBucketName(), objectName, inputStream, metadata);
            }

            // 返回文件访问URL
            return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + objectName;
        }
        catch (Exception e)
        {
            throw new RuntimeException("OSS Failed to upload file", e);
        }
    }

    @Override
    public void deleteFile(String fileUrl)
    {
        try
        {
            // 从URL中提取对象名称
            String objectName = extractObjectNameFromUrl(fileUrl);
            if (objectName != null)
            {
                ossClient.deleteObject(ossConfig.getBucketName(), objectName);
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException("OSS Failed to delete file", e);
        }
    }

    /**
     * 从URL中提取对象名称
     */
    private String extractObjectNameFromUrl(String fileUrl)
    {
        try
        {
            // URL格式: https://bucketName.endpoint/objectName
            String prefix = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/";
            if (fileUrl.startsWith(prefix))
            {
                return fileUrl.substring(prefix.length());
            }
            return null;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
